package com.bitejiuyeke.controller;

import com.bitejiuyeke.common.AppResult;
import com.bitejiuyeke.common.ResultCode;
import com.bitejiuyeke.config.AppConfig;
import com.bitejiuyeke.model.User;
import com.bitejiuyeke.services.IUserService;
import com.bitejiuyeke.utils.MD5Utils;
import com.bitejiuyeke.utils.StringUtils;
import com.bitejiuyeke.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author 比特就业课
 */

@Api(tags = "用户接口")
@Slf4j // 日志
@RestController // 返回具体数据的控制器
@RequestMapping("/user") // 一级映射路径
public class UserController {

    @Resource
    private IUserService userService;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        // 1. 判断密码与确认密码是否相同
        if (!password.equals(passwordRepeat)) {
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 2. 判断用户是否存在
        User existsUser = userService.selectByUsername(username);
        if (existsUser != null) {
            // 用户已存在
            return AppResult.failed(ResultCode.FAILED_USER_EXISTS);
        }
        // 3. 生成密码的密文
        // 生成盐
        String salt = UUIDUtils.UUID_32();
        // 生成密文
        String ciphertext = MD5Utils.md5Salt(password, salt);

        // 构造User对象
        User user = new User();
        user.setUsername(username); // 用户名
        user.setNickname(nickname); // 昵称
        user.setPassword(ciphertext); // 密码（密文）
        user.setSalt(salt); // 盐

        // 调用Service
        userService.createNormalUser(user);
        // 返回正常响应
        return AppResult.success();
    }


    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult<User> login(HttpServletRequest request,
                                 @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                                 @ApiParam("密码") @RequestParam("password") @NonNull String password) {
        // 调用Service
        User user = userService.login(username, password);
        if (user == null) {
            // 返回错误
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }

        // 获取session对象
        HttpSession session = request.getSession(true); // 没有session时创建一个
        // 把用户信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION_KEY, user);
        // 返回结果
        return AppResult.success();
    }

    @ApiOperation("获取用户详情")
    @GetMapping("/info")
    public AppResult<User> getUserInfo (HttpServletRequest request,
                                        @ApiParam("用户Id") @RequestParam(value = "id", required = false) Long id) {
        // 定义一个返回的User对象
        User user;
        // 校验Id是否为空，根据Id的值来处理不同的逻辑
        if (id == null) {
            // 从session中获取用户信息
            HttpSession session = request.getSession(false);
            user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        } else {
            // 从数据库中查询用户信息
            user = userService.selectById(id);
        }
        // 返回用户信息
        return AppResult.success(user);
    }

    @ApiOperation("用户注销")
    @GetMapping("/logout")
    public AppResult logout (HttpServletRequest request) {
        // 1. 获取session
        HttpSession session = request.getSession(false);
        // 2. 注销session
        if (session != null) {
            // 销毁session
            session.invalidate();
        }
        // 3. 返回结果
        return AppResult.success("注销成功");
    }

    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo (HttpServletRequest request,
                                 @ApiParam("用户名") @RequestParam(value = "username",required = false) String username,
                                 @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                 @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                 @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email,
                                 @ApiParam("电话号码") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                 @ApiParam("个人简介") @RequestParam(value = "remark",required = false) String remark) {
        // 非空校验，所有的参数不能同时为空
        if (StringUtils.isEmpty(username) && StringUtils.isEmpty(nickname)
                && StringUtils.isEmpty(email) && StringUtils.isEmpty(phoneNum)
                && StringUtils.isEmpty(remark) && gender == null) {
            // 返回错误描述
            return AppResult.failed("请输入要修改的内容");
        }
        // 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        // 构造更新对象
        User updateUser = new User();
        updateUser.setId(user.getId()); // id
        updateUser.setUsername(username); // 用户名
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setPhoneNum(phoneNum); // 电话号码
        updateUser.setEmail(email); // 邮箱
        updateUser.setRemark(remark); // 个人简介

        // 调用Service
        userService.modifyInfo(updateUser);
        // 获取数据库中最新的User信息
        user = userService.selectById(user.getId());
        // 更新session中的User对象
        session.setAttribute(AppConfig.USER_SESSION_KEY, user);

        // 返回成功
        return AppResult.success(user);
    }

    @ApiOperation("更新密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword (HttpServletRequest request,
                                     @ApiParam("旧密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                     @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                     @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        // 校验新密码与确认密码是否相同
        if (!newPassword.equals(passwordRepeat)) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        // 校验用户是否存在
        // 校验用户是否存在
        if (user == null || user.getDeleteState() == 1) {
            // 抛出异常
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 调用Service
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        // 销毁session
        session.invalidate();
        // 返回成功
        return AppResult.success();
    }
}
